package pushserver

import (
	"core/corestruct"
	"core/server/baseserver"
	"github.com/dubbogo/gost/log/logger"
	"sync/atomic"
	"time"
)

type PushServer struct {
	Name      string
	queue     *corestruct.Queue
	Do        func() int
	doChan    chan int32
	closeChan chan int32

	pushTimes atomic.Int32
	pushCount atomic.Int32
	doTimes   atomic.Int32
	doCount   atomic.Int32

	isRun atomic.Int32
}

func (p *PushServer) Start() {
	p.queue = &corestruct.Queue{}
	p.doChan = make(chan int32, 1000)
	p.closeChan = make(chan int32, 1)
	go func() {
		for {
			select {
			case <-p.doChan:
				if p.Do != nil {
					p.isRun.Add(1)
					var c = p.Do()
					if c > 0 {
						p.doCount.Add(int32(c))
						p.doTimes.Add(1)
						logger.Infof("推送  次数:%v 数量:%v 处理次数:%v 数量:%v 本次:%v",
							p.pushTimes.Load(),
							p.pushCount.Load(),
							p.doTimes.Load(),
							p.doCount.Load(),
							c)
					}
					p.isRun.Store(0)
				}

			case <-p.closeChan:
				logger.Infof("推送程序：%v 关闭", p.Name)
				if p.Do != nil {
					var c = p.Do()
					p.doCount.Add(int32(c))
					p.doTimes.Add(1)

				}
			}
		}

	}()
	logger.Infof("推送程序：%v 启动", p.Name)
	baseserver.AddServer(p)
}
func (p *PushServer) Close() {
	p.closeChan <- 1

}
func (p *PushServer) Push(elem interface{}) {
	p.queue.Push(elem)
	p.pushTimes.Add(1)
	p.pushCount.Add(1)
	var isrun = p.isRun.Load()
	//正在执行中
	if isrun > 0 {
		return
	}
	var t = time.Now()
	p.doChan <- 1
	var s = time.Since(t)
	if s.Seconds() > 1 {
		logger.Infof("设置doCHan超时  %v", s.Seconds())
	} else {
		logger.Infof("设置doCHan正常  %v", s.Seconds())
	}

}
func (p *PushServer) PushList(l []interface{}) {
	p.queue.PushList(l)
	p.pushTimes.Add(1)
	p.pushCount.Add(int32(len(l)))
	p.doChan <- 1
}
func (p *PushServer) Pop() interface{} {
	return p.queue.Pop()
}
func (p *PushServer) PopAll() []interface{} {
	return p.queue.PopAll()
}
